import win32security
import ntsecuritycon as con
import pywintypes

def get_file_security(file_path):
    try:
        # 获取文件的安全对象
        sd = win32security.GetFileSecurity(file_path, win32security.DACL_SECURITY_INFORMATION)
        
        # 获取DACL（自由访问控制列表）
        dacl = sd.GetSecurityDescriptorDacl()
        
        print(f"Permissions for file: {file_path}")
        
        for i in range(0, dacl.GetAceCount()):
            ace = dacl.GetAce(i)
            sid = ace[2]
            
            try:
                user, domain, type = win32security.LookupAccountSid(None, sid)
                user_info = f"{domain}\\{user}"
            except pywintypes.error as e:
                print(f"pywintypes.error occurred: {e}")
                user_info = f"SID: {sid}"
            
            access_mask = ace[1]
            
            # 解析权限
            permissions = []
            if access_mask & con.FILE_READ_DATA:
                permissions.append("READ")
            if access_mask & con.FILE_WRITE_DATA:
                permissions.append("WRITE")
            if access_mask & con.FILE_EXECUTE:
                permissions.append("EXECUTE")
            if access_mask & con.DELETE:
                permissions.append("DELETE")
            if access_mask & con.READ_CONTROL:
                permissions.append("READ_CONTROL")
            if not permissions:
                permissions.append("NO_PERMISSIONS_DETECTED")

            print(f"User/Group: {user_info}, Permissions: {', '.join(permissions)}")
    
    except Exception as e:
        print(f"Error occurred: {e}")

def main():
    import sys
    if len(sys.argv) < 2:
        print("Usage: python script.py <file_path>")
        sys.exit(1)

    file_path = sys.argv[1]
    get_file_security(file_path)

if __name__ == "__main__":
    main()